﻿using System.IO;
using GoodsService.Domain.Aggregate.Collection;
using GoodsService.Domain.Aggregate.Goods;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace GoodsService.EntityFrameworkCore
{
    /// <summary>
    /// 用户服务数据库上下文
    /// </summary>
    public class GoodsServiceDbContext : AbpDbContext<GoodsServiceDbContext>
    {
        public DbSet<Goods> Goods { get; set; }
        public DbSet<GoodsSku> GoodsSku { get; set; }
        public DbSet<Collection> Collection { get; set; }
        
        public GoodsServiceDbContext(DbContextOptions<GoodsServiceDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            
            // 配置数据库实体
            modelBuilder.Entity<Goods>(g =>
            {
                g.ConfigureByConvention();
                g.OwnsMany(goods => goods.Attributes);
            });
            modelBuilder.Entity<GoodsSku>(s =>
            {
                s.ConfigureByConvention();
                s.OwnsMany(sku => sku.Specs);
                s.HasOne(sku => sku.Goods)
                    .WithMany(goods => goods.Skus)
                    .HasForeignKey(sku => sku.ReferenceGoodsId);
            });
            modelBuilder.Entity<Collection>(c =>
            {
                c.ConfigureByConvention();
            });
        }
    }

    public class LeoGeminiDbContextFactory : IDesignTimeDbContextFactory<GoodsServiceDbContext>
    {
        public GoodsServiceDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<GoodsServiceDbContext>()
                .UseNpgsql(configuration.GetConnectionString("Default"));

            return new GoodsServiceDbContext(builder.Options);
        }

        public static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
            return builder.Build();
        }
    }
}